package com.bwie.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Active;
import com.bwie.mapper.ActiveMapper;
import com.bwie.service.ActiveService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class ActiveServiceImpl extends ServiceImpl<ActiveMapper, Active> implements ActiveService{
    @Autowired
    private ActiveMapper activeMapper;
    @Autowired
    private HttpServletRequest request;
    @Override
    public R getActiveList(PageInfoVo pageInfoVo) {
        Page<Active> activePage = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<Active> activePage1 = activeMapper.getActiveList(activePage,pageInfoVo);
        return R.OK(activePage1);
    }

    @Override
    public R addActive(Active active) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            return R.ERROR(500,"请先登录");
        }
        Active active1 = activeMapper.selectOne(
                new QueryWrapper<Active>().lambda().eq(Active::getActiveName, active.getActiveName())
        );
        if(ObjectUtils.isNotEmpty(active1)){
            return R.ERROR(500,"活动已存在");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String userName = body.get("userName", String.class);
        List<String> getTimeList = active.getGetTimeList();
        active.setCreateTime(new Date());
        active.setUpdateTime(new Date());
        active.setBeginTime(getTimeList.get(0));
        active.setEndTime(getTimeList.get(1));
        active.setFreeTimes(1);
        active.setUpdateBy(userName);
        active.setCreateBy(userName);
        activeMapper.insert(active);
        return R.OK();
    }

    @Override
    public R updateActive(Active active) {
        activeMapper.updateById(active);
        Active active1 = activeMapper.selectById(active.getActiveId());
        if(ObjectUtils.isNotEmpty(active1)){
            return R.ERROR(500,"活动已存在");
        }
        return R.OK();
    }

    @Override
    public R deleteActive(Integer actId) {
        Active active = activeMapper.selectById(actId);
        if(ObjectUtils.isEmpty(active)){
            return R.ERROR(500,"请选择活动才能进行删除");
        }
        activeMapper.deleteById(actId);
        return R.OK();
    }
}
